#include "YearTimeLine.h"


/* delegate end ########################################################################################*/


CalendarHouses::CalendarHouses( QWidget *parent  )
 : QTableWidget(12,50,parent)
{
  /////Create(owner,y);
	connect(this, SIGNAL(itemSelectionChanged()),this, SLOT(ActiveSelection()));
}

void CalendarHouses::OpenYear( const int y , int user  ) 
{
	CAnno An_Now;
	An_Now.init(y);
	An_Now.owner = user; 
	OpenYear( An_Now );
}

void CalendarHouses::OpenYear( CAnno anno ) 
{
	if (anno.size() !=12) {
	return;
	}
	
	int oldsize = InCome.size();
	
	qDebug() << " oldsize ->  " << oldsize << " owner ->" << InCome.owner;
	if (oldsize == 0 && InCome.owner == 0) {
		
	} else {
		
		  if (InCome.owner != anno.owner) {
		
						int removeyes = QMessageBox::question(this, tr("Prego confermare!"),tr("Rimpiazzare gli attributi di oggetto Nr. %1 con Nr. %2?").arg(InCome.owner).arg(anno.owner),
																																	tr("&Si"), tr("&No"),
																																	 QString(),8888,9999);
						if (removeyes == 0) {
						anno.owner = InCome.owner;
						anno.lastupdate = QDateTime::currentDateTime();
						} else {
						return;
						}
		  }
		
	qDebug() << " from ->  " << anno.lastupdate.toString();
		/////// check owner 
	}
	
	
	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
	Onloading = true;
	clearContents();
	InCome.clear();
	const int colonne = model()->columnCount();
	for (int x = 0; x < colonne; ++x)  {
	showColumn(x); 
	}
	ANNOCORRENZE_INCORSO = anno.annx;
	InCome.init( ANNOCORRENZE_INCORSO );
	InCome.owner = anno.owner;
	InCome.xyear = ANNOCORRENZE_INCORSO;
	InCome.data = anno.data;
	InCome.lastupdate = anno.lastupdate;
	InCome.data = anno.data;
	InCome.web = anno.web;
	
	setWindowTitle (QString("Anno %1 / Oggetto %2 / Ultimo aggiornamento %3").arg(ANNOCORRENZE_INCORSO).arg(InCome.owner).arg(InCome.lastupdate.toString())); 
	
	CreateRows(anno.owner,ANNOCORRENZE_INCORSO);
	/////////QApplication::restoreOverrideCursor();
	//////return;

	                         QList<CMonths> li = anno.list();
	                          for (int i=0; i<li.size(); i++) {
                               CMonths mese = li[i];
															 SetLine(mese,i);
														}
	///////qDebug() << " last_cools_active  " << last_cools_active;
	///////Onloading = false;
														
						for (int i=36; i<colonne; i++) {
							//////hideColumn ( i );
						}
	Onloading = false;  ///// Onloading = true;
	
	QApplication::restoreOverrideCursor();
}


void CalendarHouses::CreateRows( int owner , int y )
{
	ANNOCORRENZE_INCORSO = y;
	User_id = owner;
  setWindowTitle (QString("Anno %1 / Oggetto %2 / Ultimo aggiornamento %3").arg(ANNOCORRENZE_INCORSO).arg(owner).arg(InCome.lastupdate.toString())); 
  clearContents();
  setSortingEnabled(false);
	last_cools_active = 31;
	CAnno An_Now;
	An_Now.init(y);
	An_Now.owner = owner;
  setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding ); 
	Onloading = true;
	QStringList RTFdays = QStringList() << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
	QStringList testa;
	testa.clear();
	//////int base = 0;
	int dax = 0;
	for (int i=0; i<50; i++) {
		testa.append(RTFdays.at(dax));
		dax++;
		if (dax == 7) {
		dax = 0;
		}
	}
	setContextMenuPolicy(Qt::DefaultContextMenu);

	
	
	RTFmonth = QStringList() << "Gen" << "Feb" << "Mar" << "Apr" << "Mag" << "Giu" << "Lug" << "Ago" << "Set" << "Ott" << "Nov" << "Dic";
	setVerticalHeaderLabels(RTFmonth); 
	setHorizontalHeaderLabels(testa);
  bold_base_font = font();
	bold_base_font.setBold ( true );
	bold_base_font.setPointSize(7); 
	hiden_font = font();
	hiden_font.setPointSize(7); 
	setSelectionBehavior(QAbstractItemView::SelectItems);
	//////setSelectionBehavior(QAbstractItemView::SelectRows);
	resizeColumnsToContents();
	resizeRowsToContents();
}


void CalendarHouses::ActiveSelection()
{
	 qDebug() << "ActiveSelection a ........ Onloading " << Onloading;
	
	if (Onloading) {
		return;
	}
	//////////////qDebug() << "ActiveSelection.....b ... Onloading " << Onloading;
	
	selezioni.clear();
	////////////qDebug() << "ActiveSelection";
	selezioni = selectedItems();
	for (int i=0; i<selezioni.size(); i++) {
		const CDay fday = selezioni[i]->data(Qt::UserRole).value<CDay>();
		///////////////qDebug() << "select ->" << fday.dax.toString("dd.MM.yyyy");
	}
}

void CalendarHouses::Riservati()
{
	QAction *invoice = qobject_cast<QAction *>(sender());
	int ModusMake = invoice->data().toInt();
	////////qDebug() << "Riservati  " << ModusMake;
	if (selezioni.size() < 0) {
		QMessageBox::warning(0, tr("Error Calendar!"),tr("No Selection state found!"));
		return;
	} else {
		////////////qDebug() << "scrivo.........................  " << ModusMake;
		FillModus(selezioni,ModusMake,false);
	}
	
}

void CalendarHouses::Notaday()
{
	bool ok;
	QString notatxt;
	if (selezioni.size() < 0) {
		QMessageBox::warning(0, tr("Error Calendar!"),tr("No Selection state found!"));
		return;
	} else {
		////////////qDebug() << "scrivo.........................  " << ModusMake;
		               QTableWidgetItem *one = selezioni.first();
		               CDay pday = one->data(Qt::UserRole).value<CDay>();  
		               
		             EditComment *xapi = new EditComment();
		                           xapi->SetData( pday.note );
		                           
		                           xapi->show();
		                         
															 notatxt = xapi->textEdit->toPlainText();
															 xapi->deleteLater(); 
														 
		
		
		         for (int i=0; i<selezioni.size(); i++) {
		         CDay fday = selezioni[i]->data(Qt::UserRole).value<CDay>();
							 
							    notatxt.truncate(255);
							    fday.note = notatxt;
							    selezioni[i]->setData(Qt::UserRole,fday);
							    QDate Gi = fday.dax;
							    if (notatxt.size() > 0) {
                  selezioni[i]->setToolTip ( Gi.toString() + "\n" + fday.note ); 
							    selezioni[i]->setData(Qt::DecorationRole,fday.NotaVedi());
									} else {
									selezioni[i]->setToolTip ( Gi.toString()); 
							    selezioni[i]->setData(Qt::DecorationRole,QVariant());
									}
						 }
							 
		
				
	}
	
}
  

void CalendarHouses::contextMenuEvent ( QContextMenuEvent * e )
{
	  CDay aday;
	  
	
	  QMenu *TContext = new QMenu();
	  /* reservation modus    0= libero / 1= prenotato / 2= prenotato provvisorio / 3= riservato / 10 = chiuso / */
	  QAction *open0 = new QAction(tr("Rendi libero"),this);
    open0->setStatusTip(tr("Rendi libero"));
	  open0->setData(0);
    open0->setIcon ( aday.createColorToolButtonIcon(0) );
    connect(open0, SIGNAL(triggered()), this,  SLOT(Riservati()));
	
		QAction *open1 = new QAction(tr("Prenotato"),this);
    open1->setStatusTip(tr("Prenotato"));
	  open1->setData(1);
	  open1->setIcon ( aday.createColorToolButtonIcon(1) );
    connect(open1, SIGNAL(triggered()), this,  SLOT(Riservati()));
	
	  QAction *open2 = new QAction(tr("Provvisoriamente Riservato"),this);
    open2->setStatusTip(tr("Provvisoriamente Riservato"));
	  open2->setData(2);
	  open2->setIcon ( aday.createColorToolButtonIcon(2) );
    connect(open2, SIGNAL(triggered()), this,  SLOT(Riservati()));
	
		QAction *open3 = new QAction(tr("Periodo Occupato"),this);
    open3->setStatusTip(tr("Periodo Occupato"));
	  open3->setData(3);
		open3->setIcon ( aday.createColorToolButtonIcon(3) );
    connect(open3, SIGNAL(triggered()), this,  SLOT(Riservati()));
		
		QAction *open10 = new QAction(tr("Periodo Chiuso"),this);
    open10->setStatusTip(tr("Periodo Chiuso"));
	  open10->setData(10);
		open10->setIcon ( aday.createColorToolButtonIcon(10) );
    connect(open10, SIGNAL(triggered()), this,  SLOT(Riservati()));
		
		TContext->addAction(open0);
	  TContext->addAction(open1);
		TContext->addAction(open2);
		TContext->addAction(open3);
		TContext->addAction(open10);
		TContext->addSeparator ();
    TContext->addAction(tr( "Esporta come file" ), this , SLOT( ExportAsFile() ) );
		TContext->addAction(tr( "Importa da file" ), this , SLOT( ImportFromFile() ) );
		
		TContext->addSeparator ();
		
		TContext->addAction(tr( "Inerisci una nota..." ), this , SLOT( Notaday() ) );
		
    TContext->exec(QCursor::pos());
		
		
    open0->deleteLater();
		open1->deleteLater();
		open2->deleteLater();
		open3->deleteLater();
		open10->deleteLater();
    TContext->deleteLater();
    delete TContext;
}









void CalendarHouses::SetLine( CMonths M , const int row  ) 
{
  /*
    int me;
    int anno;
    QList<CDay> save_day;
  */
	QList<CDay> li = M.list();
	for (int i=0; i<li.size(); i++) {
      CDay sday = li[i];
      ////////nax.append(QString("%1").arg(sday.day()));
			SetCell(sday,i,row);
    }
	Onloading = true;
  ////////////////qDebug() << " last_cools_active  " << last_cools_active;
}

void CalendarHouses::SetCell( CDay d , const int cool ,  const int row  ) 
{
	/*
	int mex;  
    int res; 
    QDate dax;
    QDateTime xstop;
    QDateTime xstart;
    QByteArray data;
    QString note; 
	*/
	if (d.having_data()) {
	////////////qDebug() << "entra  ->" << d;
	}
	
	
	QDate Gi = d.dax;
	bool marker = false;
	if (Gi.month() == 8 && Gi.day() == 4) {
		marker = true;
	}
	
	int Weekday = Gi.dayOfWeek();
	
	QTableWidgetItem *item = new QTableWidgetItem(QString("%1.  ").arg(d.day()));
	item->setData(Qt::UserRole,d);
	
	
	
	
	                
	
	
	if (Weekday == 7) {
		item->setData (Qt::BackgroundColorRole ,QBrush(QColor("#e5e5e5"),Qt::Dense5Pattern)) ;
	}
	
	if (d.mex == 1) {
	///////InlineStyle.setForeground(QBrush(QColor(Qt::lightGray)));
		item->setData (Qt::ForegroundRole ,QColor("#e8e8e8") ) ;
		item->setTextAlignment ( Qt::AlignVCenter | Qt::AlignHCenter );
		item->setFlags ( Qt::ItemIsTristate );
		setItem(row,cool,item);
		return;
	} else {
		         if (cool >= last_cools_active) {
							 last_cools_active = cool + 1;
						 }
						 
						 if (marker) {
		         item->setData (Qt::BackgroundColorRole ,QColor("#ffddd7")) ;
	           }
						 
		item->setData(Qt::FontRole,bold_base_font);
		item->setTextAlignment ( Qt::AlignVCenter | Qt::AlignHCenter );
		item->setData (Qt::ForegroundRole ,QColor(Qt::darkBlue) ) ;
		item->setFlags ( Qt::ItemIsSelectable | Qt::ItemIsEnabled );
						 
						      if (d.note.size() > 0) {
                  item->setToolTip ( Gi.toString() + "\n" + d.note ); 
							    item->setData(Qt::DecorationRole,d.NotaVedi());
									} else {
									item->setToolTip ( Gi.toString()); 
							    //////item->setData(Qt::DecorationRole,QVariant());
									}
						 
		setItem(row,cool,item);
	}
	
	
	QList<QTableWidgetItem *> ActiveList;
  ActiveList.clear();
  ActiveList.append(item);
  FillModus(ActiveList,d.res,true);
	
}





void CalendarHouses::FillModus( QList<QTableWidgetItem *> list , const int setmodus , bool readonly )
{
	if (list.size() < 1) {
		return;
	}
	///////////qDebug() << "FillModus................." << list.size() << "........  readonly ->" << readonly  << " setmodus ->" << setmodus;
	
	/* reservation modus    0= libero / 1= prenotato / 2= prenotato provvisorio / 3= riservato / 10 = chiuso / */
	int Weekday = 0;
	for (int i=0; i<list.size(); i++) {
		CDay fday = list[i]->data(Qt::UserRole).value<CDay>();
		
		if (!readonly) {
				 fday.res = setmodus;
			   list[i]->setData(Qt::UserRole,fday);
			   //////qDebug() << "ri-scrivo  ->" << setmodus;
		} else {
			//////////qDebug() << "  scrivo readonly :-(  ->" << setmodus;
		}
		
				 
		     Weekday = fday.dax.dayOfWeek();
		     //////qDebug() << "rewrite  ->" << fday.dax.toString("dd.MM.yyyy");
		     if (setmodus == 0) {
					 list[i]->setData (Qt::BackgroundColorRole ,fday.BG(setmodus));
					 ///////selezioni[i]->setData(Qt::DecorationRole,fday.NotaVedi());
					 if (Weekday == 7) {
					 list[i]->setData(Qt::BackgroundColorRole ,QBrush(QColor("#e5e5e5"),Qt::Dense5Pattern)) ;
					 }
					 list[i]->setData(Qt::FontRole,bold_base_font);
		       list[i]->setTextAlignment ( Qt::AlignVCenter | Qt::AlignHCenter );
		       list[i]->setData (Qt::ForegroundRole ,QColor(Qt::darkBlue) ) ;
				 } else {
					 list[i]->setData (Qt::BackgroundColorRole ,fday.BG(setmodus));
					 list[i]->setData (Qt::ForegroundRole ,fday.FC(setmodus) ) ;
				 }
				 
		       
	}
	
	selezioni.clear();
	
}


void CalendarHouses::ImportFromFile()
{
	QString fixfile = QFileDialog::getOpenFileName(this, tr("Importa - Apri file"),
	                          QCoreApplication::applicationDirPath(),
	                                         "HouseCalendar_file (*.hcal)" );
    if (!fixfile.isEmpty()) {
			  QString inside;
			  QFile file(fixfile); 
								if (file.exists()) {
														if (file.open(QFile::ReadOnly | QFile::Text)) {
																inside = QString::fromUtf8(file.readAll());
															file.close();
														}
								}
			
        CAnno ExternCalendar = openAnnoBuffer(inside);
			  OpenYear( ExternCalendar );
			
		}
	
}



void CalendarHouses::ExportAsFile()
{
	int bigs = mysize();
	
	/////////////qDebug() << "bigs " << bigs;
	
	if (bigs < 1) {
	QMessageBox::warning(0, tr("Error Calendar!"),tr("No item found, Select date to reserve..."));
	return;
	}
	save_data();
	
	QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                            QCoreApplication::applicationDirPath(),
                            tr("HouseCalendar_file (*.hcal)"));
	
	if (!fileName.isEmpty() ) {
		
		    if (!fileName.endsWith(".hcal")) {
            fileName.append(".hcal");
        } 
				
				/////////return;
				
				const QString dati = saveAnnoBuffer(InCome);
				
				QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(106);
        QFile f( fileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << dati;
        f.close();
        }
		
		
		
	}
	
}



int  CalendarHouses::mysize()
{
	const int summline = model()->rowCount();
	const int colonne = model()->columnCount();
	int quant = 0;
	
	          for (int e = 0; e < summline; ++e) {
							for (int x = 0; x < colonne; ++x)  {
									QModelIndex index = model()->index(e,x);
								   CDay fday = index.data(Qt::UserRole).value<CDay>();
								   if (fday.having_data()) {
										 quant++;
									 }
							}
						}
	return quant;
}

QList<QTableWidgetItem *> CalendarHouses::selector( const int riga ) 
{
	QList<QTableWidgetItem *> ActiveList;
	ActiveList.clear();
	CurrentDayList.clear();
	/////////////qDebug() << "riga " << riga;
	
	for (int i = 0; i < model()->columnCount(); ++i) {
	QTableWidgetItem *Selectionx = item(riga,i);
									QModelIndex index = model()->index(riga,i);
		              if (index.data(Qt::DisplayRole).toString().size() > 0) {
		                             CDay fday = index.data(Qt::UserRole).value<CDay>();
								                 CurrentDayList.append(fday);
									}
		
		
		
	ActiveList.append(Selectionx);
	}
	return ActiveList;
}


void  CalendarHouses::save_data()
{
	const int summline = model()->rowCount();
	const int colonne = model()->columnCount();
	QList<CMonths> xli;
	               xli.clear();
	
	for (int e = 0; e < summline; ++e) {
		QList<QTableWidgetItem *> li = selector(e);
		///////qDebug() << "day size  " << CurrentDayList.size();
		                    CMonths dmese;
							          dmese.me = e + 1;
							          dmese.anno = ANNOCORRENZE_INCORSO;
		                    dmese.clear_all();
		                    dmese.rewrite(CurrentDayList);
		                    ///////qDebug() << "mese " << dmese.names();
		                    xli.append(dmese);
		                    delete &dmese;
	}
	
	
	///////qDebug() << "monat size  " << xli.size();
	InCome.rewrite(xli);
	
}

QString CalendarHouses::TakeConfig()
{
	save_data();
	int okday = 0;
	/////////InCome.pzip();
	/////////int okday = InCome.valid_day_size();
	qDebug() << " salva vecchio anno->" << InCome.annx << " peso-validi->" << okday;
	return QString("xxxxxxxxxxxxxxxxxxxxxxxxx");
}



















